package cn.iocoder.yudao.module.system.service.config;

import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.infra.service.config.ConfigService;
import cn.iocoder.yudao.module.infra.dal.dataobject.config.ConfigDO;
import cn.iocoder.yudao.module.infra.controller.admin.config.vo.ConfigSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.config.vo.SystemConfigSaveReqVO;
import cn.iocoder.yudao.module.system.controller.app.config.vo.AppSystemInfoRespVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * Look-IM系统配置 Service 实现类
 *
 * @author look-im
 */
@Service
@Slf4j
public class SystemConfigServiceImpl implements SystemConfigService {

    @Resource
    private AppSystemConfigService appSystemConfigService;

    @Resource
    private ConfigService configService;

    /**
     * 需要管理的配置键名列表
     */
    private static final List<String> CONFIG_KEYS = Arrays.asList(
            "sysInfo", "fileUpload", "chatInfo", "compass"
    );

    @Override
    public AppSystemInfoRespVO getSystemConfig() {
        return appSystemConfigService.getSystemInfo();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSystemConfig(SystemConfigSaveReqVO saveReqVO) {
        try {
            // 更新系统信息配置
            updateOrCreateConfig("sysInfo", "系统信息配置", JSONUtil.toJsonStr(saveReqVO.getSysInfo()));
            
            // 更新聊天配置
            updateOrCreateConfig("chatInfo", "聊天配置", JSONUtil.toJsonStr(saveReqVO.getChatInfo()));
            
            // 更新文件上传配置
            updateOrCreateConfig("fileUpload", "文件上传配置", JSONUtil.toJsonStr(saveReqVO.getFileUpload()));
            
            // 更新罗盘配置
            updateOrCreateConfig("compass", "罗盘配置", JSONUtil.toJsonStr(saveReqVO.getCompass()));
            
        } catch (Exception e) {
            log.error("更新Look-IM系统配置失败", e);
            throw new RuntimeException("更新系统配置失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetSystemConfig() {
        try {
            // 删除现有配置，让系统使用默认配置
            for (String configKey : CONFIG_KEYS) {
                ConfigDO config = configService.getConfigByKey(configKey);
                if (config != null) {
                    configService.deleteConfig(config.getId());
                    log.info("已删除配置项：{}", configKey);
                }
            }
        } catch (Exception e) {
            log.error("重置Look-IM系统配置失败", e);
            throw new RuntimeException("重置系统配置失败：" + e.getMessage());
        }
    }

    /**
     * 更新或创建配置项
     */
    private void updateOrCreateConfig(String key, String name, String value) {
        ConfigDO existingConfig = configService.getConfigByKey(key);
        
        if (existingConfig != null) {
            // 更新现有配置
            ConfigSaveReqVO updateReqVO = new ConfigSaveReqVO();
            updateReqVO.setId(existingConfig.getId());
            updateReqVO.setCategory(existingConfig.getCategory());
            updateReqVO.setName(existingConfig.getName());
            updateReqVO.setKey(existingConfig.getConfigKey());
            updateReqVO.setValue(value);
            updateReqVO.setVisible(existingConfig.getVisible());
            updateReqVO.setRemark(existingConfig.getRemark());
            
            configService.updateConfig(updateReqVO);
            log.info("已更新配置项：{}", key);
        } else {
            // 创建新配置
            ConfigSaveReqVO createReqVO = new ConfigSaveReqVO();
            createReqVO.setCategory("biz");
            createReqVO.setName(name);
            createReqVO.setKey(key);
            createReqVO.setValue(value);
            createReqVO.setVisible(true);
            createReqVO.setRemark("Look-IM " + name);
            
            configService.createConfig(createReqVO);
            log.info("已创建配置项：{}", key);
        }
    }
}